package design_6_adapter.demo1.handler.impl;


import design_6_adapter.demo1.handler.HandlerAdapter;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * Servlet 适配器
 *
 * @author wangsong
 * @email 1720696548@qq.com
 * @date 2022/4/13 9:57
 */
public class SimpleServletHandlerAdapter implements HandlerAdapter {


	private final static String MAPPING = "MAPPING";
	private final static String CLASS_INFO = "CLASS_INFO";
	private final static String WEB_XML_PATH = "src/design_6_adapter/demo1/config/web.xml";


	@Override
	public boolean supports(String uri) {
		Map<Object, Object> method = getClassAndMethod(uri);
		return method != null;
	}


	@Override
	public Object handle(String uri) {
		Map<Object, Object> map = getClassAndMethod(uri);
		Method method = (Method) map.get(MAPPING);
		Class<?> classInfo = (Class) map.get(CLASS_INFO);
		try {
			// 响应数据
			StringBuilder resp = new StringBuilder();
			// 模拟请求参数
			String request = "{'reqType':'test'}";
			method.invoke(classInfo.newInstance(), request, resp);
			return resp.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	private Map<Object, Object> getClassAndMethod(String uri) {
		// 创建SAXReader对象
		SAXReader reader = new SAXReader();
		// 加载xml文件
		Document dc = null;
		try {
			dc = reader.read(new File(WEB_XML_PATH));
			// 获取根节点
			Element e = dc.getRootElement();
			// 获取迭代器
			Iterator it = e.elementIterator();
			// 遍历迭代器，获取根节点信息
			Map<String, String> mapBend = new HashMap<String, String>();
			while (it.hasNext()) {
				Element book = (Element) it.next();
				// 获取book属性名和属性值
				//Iterator itt = book.elementIterator();
				if (book.getName().equals("servlet")) {
					Element element = book.element("servlet-name");
					Element element1 = book.element("servlet-class");
					mapBend.put(element.getText(), element1.getText());
				}
				if (book.getName().equals("servlet-mapping")) {
					Element element = book.element("servlet-name");
					Element element1 = book.element("url-pattern");
					if (element1.getText().equals(uri)) {
						// 获取类
						String classPage = mapBend.get(element.getText());
						Class<?> aClass = Class.forName(classPage);
						// 获取方法
						Method method = aClass.getDeclaredMethod("doGet", String.class, StringBuilder.class);
						// 返回
						Map<Object, Object> map = new HashMap<>();
						map.put(MAPPING, method);
						map.put(CLASS_INFO, aClass);
						return map;
					}
				}
			}
		} catch (
				Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
